package org.example.algorithm.doublepointer;

public class MoveZeroesSolution {

    public static void main(String[] args) {
        int[] nums = {1,0};
        MoveZeroesSolution solution = new MoveZeroesSolution();
        solution.moveZeroes(nums);
        for (int num: nums) {
            System.out.println(num);
        }
    }

    //直接用指针保存相对位置，然后覆盖值，最后补0
    public void moveZeroes(int[] nums) {
        int index = 0;
        for (int i=0;i<nums.length;i++) {
            if (nums[i] != 0) {
                nums[index++] = nums[i];
            }
        }
        for (int j=index;j<nums.length;j++) {
            nums[j] = 0;
        }
    }

    //遍历nums，用cnt统计0的个数，每遇到一个非零的数nums[i]，则将他与nums[i-cnt]交换位置
    public void moveZeroes4(int[] nums) {
        int count = 0;
        for (int i=0;i<nums.length;i++) {
            if (nums[i] != 0) {
                int temp = nums[i];
                nums[i] = nums[i - count];
                nums[i - count] = temp;
            }else {
                count++;
            }
        }
    }

    //简化逻辑(left == right ！= 0时依然交换)
    public void moveZeroes3(int[] nums) {
        if (nums.length <= 1) {
            return;
        }
        int left=0;
        int right=0;
        while (right < nums.length) {
            if (nums[right] != 0) {
                int temp = nums[left];
                nums[left] = nums[right];
                nums[right] = temp;
                left++;
            }
            right++;
        }
    }

    public void moveZeroes2(int[] nums) {
        if (nums.length <= 1) {
            return;
        }
        int i=0;
        int j=0;
        while (i<nums.length) {
            if (nums[i] != 0) {
                i++;
                j++;
                continue;
            }
            while (nums[j] == 0 && j<nums.length-1) {
                j++;
            }
            nums[i++] = nums[j];
            nums[j] = 0;
        }
    }
}
